<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IndexedDB 示例</title>
</head>
<body>
    <h1>IndexedDB 示例</h1>
    
    <button id="saveBtn">保存数据</button>
    <button id="loadBtn">加载数据</button>

    <div id="output"></div>

    <script>
        // 打开数据库
        const dbName = "exampleDB";
        const dbVersion = 1;
        let db;

        const request = indexedDB.open(dbName, dbVersion);

        request.onerror = (event) => {
            console.error("数据库打开失败", event);
        };

        request.onsuccess = (event) => {
            db = event.target.result;
            console.log("数据库打开成功");
        };

        request.onupgradeneeded = (event) => {
            db = event.target.result;
            if (!db.objectStoreNames.contains("items")) {
                db.createObjectStore("items", { keyPath: "id", autoIncrement: true });
                console.log("创建了 object store");
            }
        };

        // 保存数据到 IndexedDB
        const saveData = () => {
            const transaction = db.transaction(["items"], "readwrite");
            const store = transaction.objectStore("items");
            const data = { name: "张三", age: 30 };

            const request = store.add(data);
            request.onsuccess = () => {
                console.log("数据保存成功");
                alert("数据保存成功");
            };
            request.onerror = (event) => {
                console.error("数据保存失败", event);
            };
        };

        // 加载数据
        const loadData = () => {
            const transaction = db.transaction(["items"], "readonly");
            const store = transaction.objectStore("items");

            const request = store.getAll();
            request.onsuccess = (event) => {
                const data = event.target.result;
                const output = document.getElementById("output");
                output.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
            };
            request.onerror = (event) => {
                console.error("数据加载失败", event);
            };
        };

        // 绑定按钮事件
        document.getElementById("saveBtn").addEventListener("click", () => {
            if (db) {
                saveData();
            } else {
                alert("数据库未打开成功");
            }
        });

        document.getElementById("loadBtn").addEventListener("click", () => {
            if (db) {
                loadData();
            } else {
                alert("数据库未打开成功");
            }
        });
    </script>
</body>
</html>
